//
//  PopularProductController.m
//  HelloWorld
//
//  Created by Beomjun Kim on 09. 09. 21.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "ProductController.h"
#import "ProductDetailController.h"
#import "XmlUtil.h"
#import "XMLParser.h"
#import "TreeNode.h"
#import "ProductListModel.h"


#define URLSTRING_TAG		999

@implementation ProductController

@synthesize url;
@synthesize resultList;

-(ProductController *) initWithTitle: (id) title
							 withUrl: (NSString *) xmlUrl
{
	self = [super init];

	self.title = title;
	self.url = xmlUrl;

	[self.tabBarItem initWithTitle:self.title image:nil tag:0];
	
	return self;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	return [self.resultList count];
}

- (void) modCell:(UITableViewCell *)aCell withIndex:(int)index
{
	ProductListModel *product = [self.resultList objectAtIndex:index];
	
	// 이미지가 있을 경우에는 해당 URL로부터 직접 갖고 오고, 없을 경우에는 디폴트 이미지를 보여준다.
	//NSURL *url = [NSURL URLWithString:product.image1];
	NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:product.image1]];
	
	UIImage *image;

	if(data){
		image = [UIImage imageWithData:data];
		//[data release];

		UIImageView *view = [[UIImageView alloc] initWithImage:image];
		
        [view setFrame:CGRectMake(2.0f, 2.0f, 60.0f, 60.0f)];
        [aCell addSubview:view];
        
		[view release];
        //[image release];
		
	} else {
		//img =  [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png" inDirectory:@"/"]];		
	}
	//[data autorelease];
	
	//aCell.image = image;
	
	
	// 이름에 해당하는 UILabel 생성
	CGRect tRect1 = CGRectMake(70.0f, 5.0f, 230.0f, 25.0f);
	UILabel *title1 = [[UILabel alloc] initWithFrame:tRect1];
	[title1 setText:product.name];
	[title1 setTextAlignment:UITextAlignmentLeft];
	[title1 setFont: [UIFont fontWithName:@"American Typewriter" size:18.0f]];
	[title1 setBackgroundColor:[UIColor clearColor]];
	
	// 가격에 해당하는 UILabel 생성
	CGRect tRect2 = CGRectMake(70.0f, 40.0f, 125.0f, 20.0f);
	UILabel *title2 = [[UILabel alloc] initWithFrame:tRect2];
	title2.tag = URLSTRING_TAG;
	[title2 setText:[NSString stringWithFormat:@"%@ 원", product.price]];
	[title2 setTextAlignment:UITextAlignmentLeft];
	[title2 setTextColor:[UIColor blueColor]];
	[title2 setFont: [UIFont fontWithName:@"Helvetica" size:14.0f]];
	[title2 setBackgroundColor:[UIColor clearColor]];	
	
	// 남은시간에 해당하는 UILabel 생성
	CGRect tRect3 = CGRectMake(180.0f, 40.0f, 120.0f, 20.0f);
	UILabel *title3 = [[UILabel alloc] initWithFrame:tRect3];
	[title3 setText:[NSString stringWithFormat:@"남은시간 : %@", product.remTime]];
	[title3 setTextAlignment:UITextAlignmentRight];
	[title3 setFont: [UIFont fontWithName:@"Helvetica" size:14.0f]];
	[title3 setBackgroundColor:[UIColor clearColor]];
	
	// 꺽쇠 해당하는 UILabel 생성
	CGRect rightRect = CGRectMake(300.0f, 2.0f, 20.0f, 60.0f);
	UILabel *rightTitle = [[UILabel alloc] initWithFrame:rightRect];
	[rightTitle setText:@">"];
	[rightTitle setTextAlignment:UITextAlignmentLeft];
	//[rightTitle setTextColor:[UIColor redColor]];
	[rightTitle setFont: [UIFont boldSystemFontOfSize:14.0f]];
	[rightTitle setBackgroundColor:[UIColor clearColor]];
	
	// 셀에 UILabel을 추가한다
	[aCell addSubview:title1];
	[aCell addSubview:title2];
	[aCell addSubview:title3];	
	[aCell addSubview:rightTitle];	
	
	[title1 release];
	[title2 release];
	[title3 release];
	[rightTitle release];
}

/*
 *	Delegate 메소드
 *
 *	- 테이블의 Row 수만큼 자동으로 호출이 된다.
 *  - 재사용이 되므로, 재사용되는 부분을 알맞게 코딩을 해야 한다.
 */
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:@"any-cell"];
	cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"any-cell"] autorelease];

	if (cell == nil) {
	} else {
		
		//[cell r
	}
	
	// Index를 넘겨서 해당 값을 커스텀 셀을 구성한다.
	[self modCell:cell withIndex:indexPath.row];
	
	return cell;
}

/*
 *  Delegate Methods - This doesn't do anything, plus Apple has removed App launching from the SDK arsenal
 */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath 
{
	ProductListModel *product = [self.resultList objectAtIndex:newIndexPath.row];
	printf("User selected code %s, name %s\n",  [product.index UTF8String], [product.name UTF8String]);
	
	// 카테고리별 상품
	NSString *requestUrl = [NSString stringWithFormat:@"http://www.haroohana.com/iphone/iphone_pdtdetail.php?pdtindex=%@", product.index];
	ProductDetailController *bControl1 = [[ProductDetailController alloc] initWithTitle:product.name
																	withUrl:requestUrl];
	[[self navigationController] pushViewController:bControl1 
										   animated:YES];
	
	[bControl1 release];
}


/*
 * 데이터 소스 설정
 */
-(void) setDataSource
{
	// XML 결과를 가져온다.
	XMLParser *parser = [[XMLParser alloc] init];
	TreeNode *root = [parser parseXMLFile:[NSURL URLWithString:self.url]];
	self.resultList = [[[NSMutableArray alloc] init] autorelease];
	
	// rss로 한번 감싸여져 있다.
	root = [[root children] objectAtIndex:0];
	
	TreeNode *rootKey = [[root children] objectAtIndex:0];
	if([rootKey.key isEqual:@"poppdt"]){
		
	} else if([rootKey.key isEqual:@"catepdtlist"]){
		root = [[root children] objectAtIndex:0];
	}

	// catepdtlist로 한번 감싸여져 있다.
	// root = [[root children] objectAtIndex:0];

	int size = [[root children] count];	
	printf("Product list size : %d\n",  size);

	for(int i=0; i<size; i++) 
	{
		TreeNode *list = [[root children] objectAtIndex:i];
		
		if([list.key isEqual:@"product"]){
			ProductListModel *model = [[ProductListModel alloc] init];
			
			model.index = [XmlUtil stringForPath:@"pdtindex" ofNode:list];
			model.name = [XmlUtil stringForPath:@"name" ofNode:list];
			model.price = [XmlUtil stringForPath:@"price" ofNode:list];
			model.remTime = [XmlUtil stringForPath:@"remTime" ofNode:list];
			model.image1 = [XmlUtil stringForPath:@"image1" ofNode:list];
			model.cnt = [XmlUtil stringForPath:@"cnt" ofNode:list];
			
			[self.resultList addObject:model];
			
		// 인기상품
		} else if([list.key isEqual:@"poppdt"]){
			ProductListModel *model = [[ProductListModel alloc] init];
			
			model.index = [XmlUtil stringForPath:@"pdtindex" ofNode:list];
			model.name = [XmlUtil stringForPath:@"name" ofNode:list];
			model.price = [XmlUtil stringForPath:@"price" ofNode:list];
			model.remTime = [XmlUtil stringForPath:@"remTime" ofNode:list];
			model.image1 = [XmlUtil stringForPath:@"image1" ofNode:list];
			model.cnt = [XmlUtil stringForPath:@"cnt" ofNode:list];
			
			[self.resultList addObject:model];
		}
	}
	
	/*
	[self.root dump];

	self.categoryArray = [NSArray arrayWithObjects:
						  @"SEIKO ALBA[오늘만특가 78%세일 100개한정]", 
						  @"젤리케이스 오늘만특가 1,500원", 
						  @"PUMA", 
						  @"오뚜기 3분 시리즈 10개 9,900원 + 무료배송", 
						  @"POLO",
						  @"오리털 슬리핑백",
						  @"[09NEW OTTO] 신발건조랙2개세트 [614024]",
						  @"국화차/홍차/루이보스티",
						  @"눈썹 특집",
						  @"[9월 행사] SKT 무료폰 이벤트",
						  nil];
	
	NSError *error;
	NSData *data = [NSData dataWithContentsOfFile:@"/PopularProductList.xml" options:0 error:&error];
	
	if (data == nil) {
		NSLog(@"Read failed: %@", [error localizedDescription]);
	} else {
		NSLog(@"Read success");
	}
	*/
	// 가져온 XML을 분석한다.
	/*
	NSXMLDocument *doc;
	doc = [[NSXMLDocument alloc] initWithData:data 
									  options:0 
										error:&error];
	
	if(INNER_DEBUG)
		NSLog(@"NSXMLDocument\n%@\n\n", [doc XMLString] );
		//printf("NSXMLDocument\n%s\n\n", [[doc XMLString] UTF8String]);
		
	
	// 리스트에 해당하는 객체를 저장한다.
	itemNodes = [[doc nodesForXPath:@"root/list" error:&error] retain];
	*/
	/*
	for (int i =0; i<[itemNodes count]; i++) {
		NSLog(@"Node : %@", [itemNodes objectAtIndex:i] );
	}
	*/
	/* 디렉토리 위치 변경
	[[NSFileManager defaultManager] changeCurrentDirectoryPath:@"/Applications/Haroohana.app"];
	*/
	
	/* 파일 검색
	NSString *file;
	NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:@"/Applications"];
	while (file = [dirEnum nextObject]) {
		NSLog(@"Read failed: %@", [file pathComponents]);
	}
	*/
	
	/* 현재 위치 
	NSLog(@"Read failed: %@", [[NSFileManager defaultManager] currentDirectoryPath]);
	*/
	
	/* 위치에 대한 이름
	NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *displayNameAtPath = [fileManager displayNameAtPath:@"/"];
    NSLog(@"%@", displayNameAtPath);
	*/
	
	/* 위치에 대한 디렉토리 출력
	NSArray *currentDirectory = [fileManager directoryContentsAtPath:@"/"];
	for (int i =0; i<[currentDirectory count]; i++) {
		NSLog(@"%@", [currentDirectory objectAtIndex:i] );
	}
	*/
}


- (void)loadView
{
	[super loadView];
	[self.tableView setRowHeight:64];
	
	[self setDataSource];
}

@end